﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace CoreLib.Communication.Packets
{
    /// <summary>
    /// Pool of instances of the Packet class
    /// </summary>
    public class PacketRecycler
    {
        private static ConcurrentQueue<Packet> packetQueue = new ConcurrentQueue<Packet>();

        /// <summary>
        /// Adds a packet to the pool to make it reusable
        /// </summary>
        /// <param name="recycledPacket">packet for recycle</param>
        public static void Push(Packet recycledPacket)
        {
            packetQueue.Enqueue(recycledPacket);
        }

        /// <summary>
        /// Gets a pre-created instance of the packet class
        /// </summary>
        /// <param name="requiredSize">length required for the packet</param>
        /// <returns></returns>
        public static Packet Pop(int requiredSize)
        {
            Packet returning;
            if (!packetQueue.TryDequeue(out returning))
                returning = new Packet(Packet.MaxSize);
            returning.Reset(requiredSize);
            return returning;
        }
    }
}
